﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using System.IO;
using Common;

public partial class website_admin_knowlegebase_kbarticleslist : PageBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Expires = -1;
        PageBegin();

        switch (RequestBase.GetFormString("otype"))
        {
            case "loadingdata":
                LoadingData();
                break;
            case "deleteitems":
                Delete();
                break;
        }

        if (!IsPostBack)
            CategoryDataBind();
    }

    #region 类别列表数据绑定
    void CategoryDataBind()
    {
        DataTable dt = BLL.CommonBLL.Select("KbCategoryBase", "*", " AND DeletionStateCode = 0 AND CategoryType = 1 ORDER BY LineNum ASC");
        if (dt != null && dt.Rows.Count > 0)
        {
            selCategoryList.Items.Add(new ListItem("\t+\t" + dt.Select("CategoryNumber = '" + RequestBase.GetQueryString("c_number") + "'")[0]["CategoryName"].ToString(), RequestBase.GetQueryString("c_number")));

            int layer = int.Parse(dt.Select("CategoryNumber = '" + RequestBase.GetQueryString("c_number") + "'")[0]["Layer"].ToString()) + 1;

            DropdownlistDataBind(layer, dt.Select("CategoryNumber = '" + RequestBase.GetQueryString("c_number") + "'")[0]["CategoryId"].ToString(), dt);
        }
        else
            DropdownlistDataBind(1, "00000000-0000-0000-0000-000000000000", dt); 
    }
    /// <summary>
    /// 类别列表邦定
    /// </summary>
    /// <param name="intLayer">级别</param>
    /// <param name="parentId">父目录ID</param>
    /// <param name="dt">目录数据表</param>
    void DropdownlistDataBind(int intLayer, string parentId, DataTable dt)
    {
        if (dt == null)
            return;

        DataRow[] dr = dt.Select("Layer = " + intLayer.ToString() + " AND ParentId = '" + parentId + "'");

        ArrayList al = new ArrayList();
        ListItem li;

        string str = ""; int intCategoryLayerID = 0;
        foreach (DataRow d in dr)
        {
            str = "　| ";
            intCategoryLayerID = int.Parse(d["Layer"].ToString());
            if (intLayer == 1)
                str = " + ";
            for (int i = 1; i < intLayer * intLayer; i++)
                str += "--";


            li = new ListItem("\t" + str + "\t" + d["CategoryName"].ToString(), d["CategoryNumber"].ToString());

            selCategoryList.Items.Add(li);
            DropdownlistDataBind(intCategoryLayerID + 1, d["CategoryId"].ToString().Trim(), dt);
        }
    }
    #endregion

    #region 信息绑定
    void LoadingData()
    {
        string ctrl = "~/website_admin/knowlegebase/_controls/ctlKbArticleList.ascx";

        string SQL = " AND DeletionStateCode = 0";

        if (!string.IsNullOrEmpty(RequestBase.GetFormString("title")))
        {
            SQL += " AND Title LIKE '%" + RequestBase.GetFormString("title") + "%'";
        }


        SQL += " AND CategoryNumber LIKE '" + RequestBase.GetFormString("category") + "%'";

        Control uc_rep = LoadControl(ctrl);

        Repeater rptArticleList = (Repeater)uc_rep.FindControl("rptArticleList");

        DBUtility.Pagination pagination = new DBUtility.Pagination();
        try
        {
            if (!string.IsNullOrEmpty(RequestBase.GetString("index")))
                pagination.Sequence = Convert.ToInt32(RequestBase.GetString("index"));
            else
                pagination.Sequence = 1;

            pagination.ItemUnit = "条记录";
            pagination.SortSentence = " ORDER BY PublishDate DESC";
            pagination.Primarykey = "ArticleId";
            pagination.SearchField = "*";
            pagination.TableName = "vw_KbArticleBaseForList";
            if (!string.IsNullOrEmpty(RequestBase.GetString("pagesize")))
                pagination.PageSize = Convert.ToInt32(RequestBase.GetString("pagesize"));
            else
                pagination.PageSize = 20;
            pagination.UrlStr = "";
            pagination.ImagesPath = "../_imgs/grid/";
            pagination.SearchSentence = SQL.Trim();

            rptArticleList.DataSource = pagination.GetDataTable();
            rptArticleList.DataBind();

            pagination.PageBarFlexigrid();
            uc_rep.GetType().GetProperty("PaginationBar").SetValue(uc_rep, pagination.PageBar, null);

            StringBuilder strb = new StringBuilder();
            StringWriter sw = new StringWriter(strb);
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            rptArticleList.RenderControl(htw);

            BLL.AjaxHelper.ResponseWrite(strb.ToString());
        }
        catch (System.Threading.ThreadAbortException err)
        {
            //nothing   to   do   
        }
        catch (Exception err)
        {
            BLL.AjaxHelper.ResponseWrite(err.Message);
        }
    }
    #endregion

    #region 删除
    /// <summary>
    /// 删除目录
    /// </summary>
    void Delete()
    {
        string itemsid = RequestBase.GetFormString("itemsid").Replace("'", "").Replace("'", "");

        string res = "";
        foreach (string objectid in itemsid.Split(','))
        {
            RemoveAttachment(objectid);

            /// 逻辑删除商品记录
            BLL.KbArticleBase.Delete(objectid);
  
            res = "succeeded";
        }

        BLL.AjaxHelper.ResponseWrite(res); 
    }
    void RemoveAttachment(string objectid)
    {
        Model.KbArticleBase _obj = BLL.KbArticleBase.GetObjById(objectid); 
        string _cnumber = _obj.CategoryNumber;
        string _filepath = "", _titlepicpath = "";

        _filepath = ConfigurationManager.AppSettings["ProductImages"].ToString();
        _titlepicpath = ConfigurationManager.AppSettings["TitleImage"].ToString();

        if (_obj.TitlePic.Split('*').Length > 1 && _obj.TitlePic.Split('*')[1] != "")
        {
            if (File.Exists(Server.MapPath("../../" + _titlepicpath + _obj.TitlePic.Split('*')[1])))
            {
                File.Delete(Server.MapPath("../../" + _titlepicpath + _obj.TitlePic.Split('*')[1]));
            }
        }

        if (_filepath != "")
            /// 清空产品图片
            BLL.AttachmentsBase.RemoveFilesByRegardingObjectId(objectid, _filepath);
    }
    #endregion
}
